<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%String path = request.getContextPath();%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>

<%--默认的费用项--%>
<div class="fieldBox col_100" id="defaultFeeDiv">
    <div class="sqPanel">
        <div id="detailGrid">
            <div id="ligergrid_def_fee_sett" class="sq-grid"></div>
        </div>
    </div>
</div>
<!-- 添加结清费用项 -->
<div class="fieldBox col_100">
    <div class="sqPanel">
        <div class="sqPanel_head inL" style="margin:0 0 30px 0">
            <div class="btnsBox inLC">
                <span id="addBtn" class="sq-button sq-button-round operation"><!-- <i class="sqBtnIco_3"></i> -->添加</span>
                <span id="delBtn" class="sq-button sq-button-round operation"><!-- <i class="sqBtnIco_7"></i> -->删除</span>
            </div>
        </div>
        <div>
            <div id="ligergrid_fee_sett" class="sq-grid"></div>
        </div>
    </div>
</div>
<div class="fieldBox col_100">
    <div class="label">应收结清款</div>
    <div class="field">
        <input style="display: none" id="baseSettAmt" value="${pay.totalSettAmt/100}">
        <span id="totalSettAmt">
            ${pay.totalSettAmt/100}
        </span>
    </div>
</div>

<script type="text/javascript">
    var basePath = '<%=path%>';
    var def_fee_grid, feeSettGrid;
    var flow = '${flow}';

    var settFeeTypCdListJSON = [];
    <c:if test="${not empty settFeeTypCdListJSON}">
    settFeeTypCdListJSON = ${settFeeTypCdListJSON};
    </c:if>

    $(function () {
        initDefFeeSettGrid();
        initAddFeeSettGrid();
    });

    // 新增费用项，页面操作，无后台交互
    $("#addBtn").click(function (event) {
        feeSettGrid.addRow({
            id: '',
            feeTypCd: '',
            feeAmt: ''
        });
    });
    // 删除费用项，页面操作，无后台交互
    $("#delBtn").click(function (event) {
        var selectedRows = feeSettGrid.getSelectedRows();
        if (selectedRows.length < 1) {
            $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_SELECT_ONLY_A_ROW, SQ_type: "warring"});
            return;
        }
        $.ligerDialog.confirm(LogUtils.LOG_CMM_DELETE_CONFIRM, function (flag) {
            if (flag == false) return;
            // 以下两句必须都写上
            feeSettGrid.deleteSelectedRow();
            feeSettGrid.removeRange(feeSettGrid.getSelectedRows());
            modifySettValue();
        });
    });

    //修改结清款
    function modifySettValue() {
        var total = 0;
        var rows = feeSettGrid.rows;
        for (var i = 0; i < rows.length; i++) {
            var feeAmt = rows[i].feeAmt;
            if (typeof feeAmt == "number") {
                var capFlow = rows[i].codeAttr1 == undefined ? rows[i].capFlow : rows[i].codeAttr1;
                if (capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT) {
                    total -= feeAmt;
                }
                if (capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_IN) {
                    total += feeAmt;
                }
            }
        }
        var settAmt = $("#baseSettAmt").val();
        var totalSetAmt = NumberUtils.add(NumberUtils.sub(settAmt, initSettleFeeAmt), total);
        $("#totalSettAmt").text(totalSetAmt);
    }

    var initSettleFeeAmt = 0;
    function initAddFeeSettGrid() {
        var params = {};
        params.paySchId = paySchId;
        params.prjId = prjId;
        feeSettGrid = $("#ligergrid_fee_sett").ligerGrid({
            method: 'get',
            parms: params,
            url: basePath+'/project/prjPrdPaySchD/getPrjPrdPaySchSettFeeList.do',
            columns: [
                {
                    display: '费用类型', name: 'feeTypCd', minWidth: 80,
                    editor: {
                        type: 'select',
                        data: settFeeTypCdListJSON,
                        valueField: 'code',
                        textField: 'codeNm'
                    },
                    valueField: 'feeTypCd',
                    textField: 'feeTypCdNm',
                    render: function (item) {
                        return item.feeTypCdNm;
                    }
                },
                {
                    display: '金额', name: 'feeAmt', minWidth: 80, type: 'numberbox',
                    editor: {
                        type: 'number',
                        precision: 2,
                        toFix: true,
                        onToFix: function () {
                            top.$.ligerDialog.SQalert({SQ_type: "warning", content: "小数点后面最多2小数！"});
                        }
                    },
                    render: function (item) {
                        if (StringUtils.isEmpty(item.feeAmt)) {
                            return;
                        }
                        var amt = renderAmt(null, null, item.feeAmt * 100);
                        if (item.capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT
                            || item.codeAttr1 == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT) {
                            amt = "<span style='color:red'>-" + amt + "</span>";
                        }
                        return amt;
                    }
                },
                { display: '未核销金额', name: 'arAmt', minWidth: 80, type: 'currency', render: function (item) {
                        if (StringUtils.isEmpty(item.arAmt)) {
                            return;
                        }
                        var amt = renderAmt(null, null, item.arAmt);
                        return amt;
                    }
                }
            ],
            onBeforeEdit: function (e) {
                e.column.editor.readonly = readOnlyFlag;
            },
            onAfterEdit: function (e) {
                var colNanme = e.column.columnname;
                if (e.selected && e.column.columnname == "feeTypCd") {
                    e.record.codeAttr1 = e.selected.codeAttr1;
                    e.record.feeTypCd = e.selected.code;
                }
                if (e.record.isSysDef == 1 && colNanme != "feeAmt") {
                    e.column.editor.readonly = true;
                } else {
                    e.column.editor.readonly = false;
                }
                feeSettGrid.updateCell('feeAmt', e.record.feeAmt, e.record);
                feeSettGrid.updateCell('capFlow', e.record.codeAttr1, e.record);
                if (StringUtils.isNotEmpty(e.record.feeAmt)) {
                    modifySettValue();
                }
            },
            onSuccess: function (rowDatas, grid) {
                var data = rowDatas.rows;
                initSettleFeeAmt = 0;
                if (data != null) {
                    for (var i = 0; i < data.length; i++) {
                        var feeAmt = data[i].feeAmt;
                        if (data[i].capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT) {
                            feeAmt = -1 * feeAmt;
                        }
                        initSettleFeeAmt += feeAmt;
                    }
                }
            },
            usePager: false,
            pageSize: 100,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: 300,
            heightDiff: -2,
            enabledEdit: true,
            isScroll: false,
            checkbox: true,
            allowUnSelectRow: true,
            alternatingRow: true,
            usePagerOnLessPagesize: false,
        });
    }

    // 保存添加的费用项
    function saveSettleData() {
        $.ligerDialog.confirm("确定要保存吗？", function (flag) {
            if (flag == false) return;
            var data = {};
            data["prjId"] = prjId;
            data["paySchId"] = paySchId;
            var updated = feeSettGrid.getUpdated();// 更新的数据
            var added = feeSettGrid.getAdded();    // 新增的数据
            var deleted = feeSettGrid.getDeleted();// 删除的数据,删除方法调用deleteSelectedRow(),不然这里获取不到
            updated.push.apply(updated, added);
            if (deleted != undefined && deleted.length > 0) {
                updated.push.apply(updated, deleted);
            }
            /*if (updated.length == 0) {
                $.ligerDialog.SQalert({content: "没有需要修改的费用项数据！", SQ_type: "warring"});
                return;
            }*/
            data["settFeeList"] = JSON.stringify(updated);
            data["totalSettAmt"] = $("#totalSettAmt").text().trim();
            data["paySchId"] = paySchId;
            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: data,
                url: basePath + "/project/prjPrdPaySchD/addOrRemoveSettFee.do",
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({ content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting" });
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        $.ligerDialog.SQalert({
                            content: msg.info,
                            SQ_type: "success",
                            SQ_showButtons: true,
                            SQ_onBtnclick: function () {
                                feeSettGrid.reload();
                                def_fee_grid.reload();
                                $("#baseSettAmt").val(msg.data);
                                $("#totalSettAmt").text(msg.data);
                            }
                        });
                    } else {
                        UIUtils.alertErrorHold1(msg.info);
                    }
                }
            });
        });
    }

    // 初始化默认的费用项
    function initDefFeeSettGrid() {
        def_fee_grid = $("#ligergrid_def_fee_sett").ligerGrid({
            columns: [
                {display: '费用类型', name: 'feeTypCdNm', minWidth: 80},
                {display: '金额', name: 'feeAmt', minWidth: 80, type: 'numberbox',
                    render: function (item) {
                        var amt = item.feeAmt;
                        if (flow == CommonConstant.C_YN_Y_1) {
                            amt = renderAmt(null, null, item.feeAmt*100);
                        } else {
                            amt = renderAmt(null, null, item.feeAmt);
                        }
                        if (item.capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT
                            || item.codeAttr1 == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT) {
                            amt = "<span style='color:red'>-" + amt + "</span>";
                        }
                        return amt;
                    }
                },
                {display: '', name: '', minWidth: 80}
            ],
            usePager: false,
            pageSize: 100,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: 300,
            heightDiff: -2,
            enabledEdit: true,
            isScroll: false,
            checkbox: false,
            rownumbers: true,
            allowUnSelectRow: true,
            alternatingRow: true,
            usePagerOnLessPagesize: false
        });
        if (flow == CommonConstant.C_YN_Y_1) {
            def_fee_grid.set({
                method: 'get',
                parms: {paySchId: paySchId},
                url: basePath + '/project/prjPrdPaySchD/getPrjPrdPaySchDefSettFeeList.do'
            });
        } else {
            var defSetFeeAmtData = {
                "rows": [
                    {"feeTypCdNm": "优惠金额1", "feeAmt": '${pay.discountAmt1}', "capFlow": '2'},
                    {"feeTypCdNm": "优惠金额", "feeAmt": '${pay.discountAmt}', "capFlow": '2'},
                    {"feeTypCdNm": "违约金", "feeAmt": '${pay.breachAmt}', "capFlow": '1'}
                ],
                "total": 2
            };
            def_fee_grid.loadData(defSetFeeAmtData);
        }
    }

</script>